package com.hethongviet.vending.pages;

import java.io.InputStream;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.google.android.DemoKit.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.OnUsbListener;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.db.AccountSQLite;
import com.hethongviet.vending.helper.db.BoxSQLite;
import com.hethongviet.vending.helper.db.ProductSellSQLite;
import com.hethongviet.vending.helper.dialog.DialogList;
import com.hethongviet.vending.helper.dialog.DialogMessage;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.helper.dialog.DialogMessageTimeOut;
import com.hethongviet.vending.model.Account;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.BoxItem;
import com.hethongviet.vending.model.ProductSell;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONSTANTS;
import com.hethongviet.vending.network.Network;

public class UserActivity extends GeneralActivity implements OnUsbListener
{
	private LinearLayout _listViewProduct1 = null;
	private LinearLayout _listViewProduct2 = null;
	private LinearLayout _listViewProduct3 = null;

	private Button _buttonPageBack = null;
	private Button _buttonPageNext = null;
	private Button _buttonPageTemp = null;
	private Button _buttonPayIn = null;

	private TextView _textHaveNoProduct = null;
	private TextView _textUserAmount = null;

	private List<BoxItem> _productList = null;

	private TimerOutUtils _timerOutUtils = null;

	private Timer _timerOutProductDelevery = null;
	private int _pageCurrent = 0;
	private int _totalPages = 0;

	private DialogMessage dialogMessageConfirmBuy = null;

	private ProductSell _productSell = null;

	private AccountSQLite _accountSqLite = null;
	private BoxSQLite _boxSqLite = null;
	private ProductSellSQLite _productSellSQLite = null;

	private boolean isBoughtProduct = false;
	private boolean isDetailProduct = false;

	public UserActivity()
	{
		_accountSqLite = new AccountSQLite(this);
		_boxSqLite = new BoxSQLite(this);
		_productSellSQLite = new ProductSellSQLite(this);
	}

	private static class ViewHolder
	{
		TextView textProductName = null;
		TextView textProductPrice = null;
		ImageView imageViewProduct = null;
	}

	private void showMessageError()
	{
		setResult(RESULT_OK);
		showDialogWithCatch(R.string.message_put_command_error);
		_timerOutUtils.startTimeOutDialog();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		isBoughtProduct = false;

		setContentView(R.layout.page_user);

		findViewById(R.id.button_back).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				if (_productList != null && _productList.size() != 0)
				{
					showDialogWithCatch(R.string.message_exit_confirm_user);
				}
				else
				{

					Utils.debug("Finish user!!!!!!!!!!!!!!!!2");
					setResult(RESULT_OK);
					finish();
				}
			}
		});

		if (AppMain.getInstance().getCurrentAccount() == null)
		{

			Utils.debug("Finish user!!!!!!!!!!!!!!!!3");
			setResult(RESULT_CANCELED);
			finish();
		}

		TextView textViewUsername = (TextView) findViewById(R.id.text_user_name);
		_textUserAmount = (TextView) findViewById(R.id.text_user_amount);

		if (AppConfig.USE_ACCOUNT_MONEY)
		{
			textViewUsername.setText(AppMain.getInstance().getCurrentAccount().getName());
			textViewUsername.setVisibility(View.VISIBLE);
			_textUserAmount.setText(AppMain.getInstance().getCurrentAccount().getAmount()
					+ "VND");
			_textUserAmount.setVisibility(View.VISIBLE);
		}
		else
		{
			_textUserAmount.setVisibility(View.GONE);
			textViewUsername.setVisibility(View.GONE);
		}

		_listViewProduct1 = (LinearLayout) findViewById(R.id.layout_list_product_1);
		_listViewProduct2 = (LinearLayout) findViewById(R.id.layout_list_product_2);
		_listViewProduct3 = (LinearLayout) findViewById(R.id.layout_list_product_3);

		_buttonPageBack = (Button) findViewById(R.id.button_page_back);
		_buttonPageNext = (Button) findViewById(R.id.button_page_next);
		_buttonPageTemp = (Button) findViewById(R.id.button_page_temp);

		_buttonPayIn = (Button) findViewById(R.id.button_user_pay_in);

		if (!AppConfig.USE_ACCOUNT_MONEY)
		{
			_buttonPayIn.setVisibility(View.GONE);
		}

		_textHaveNoProduct = (TextView) findViewById(R.id.text_have_no_product);

		_buttonPageBack.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				_pageCurrent--;
				if (_pageCurrent < 0)
				{
					_pageCurrent = 0;
					_buttonPageBack.setVisibility(View.GONE);
					_buttonPageTemp.setVisibility(View.GONE);
				}
				else
				{
					_buttonPageNext.setVisibility(View.VISIBLE);
				}
				showProducts();
			}
		});

		_buttonPageNext.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				_pageCurrent++;
				if (_pageCurrent == _totalPages)
				{
					_pageCurrent = _totalPages - 1;
					_buttonPageNext.setVisibility(View.GONE);
					_buttonPageTemp.setVisibility(View.GONE);
				}
				else
					_buttonPageBack.setVisibility(View.VISIBLE);
				showProducts();
			}
		});

		_buttonPayIn.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(UserActivity.this,
						InputTextActivity.class);

				Bundle bundle = new Bundle();
				bundle.putInt(InputTextActivity.KEY_INPUT_TYPE,
						InputTextActivity.INPUT_USER_AMOUNT);
				bundle.putInt(Constant.EXTRA_FINISH, 1);
				intent.putExtras(bundle);

				startActivityForResult(intent,
						InputTextActivity.INPUT_USER_AMOUNT);

			}
		});

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, true);

		_timerOutUtils.startTimerNotOperating();
		_timerOutUtils.startTimerOutUser();

		showDialogWithCatch(R.string.message_welcome_login);
	}

	private void processBuyProduct()
	{
		// Intent intent = new Intent(UserActivity.this,
		// DetailProductActivity.class);
		// startActivityForResult(intent, REQUEST_SELL);

		showProgress(this);

		Box currentBox = AppMain.getInstance().getCurrentBox();
		long price = AppMain.getInstance().getCurrentBoxItem().getProduct().getPrice();

		if (AppConfig.USE_ACCOUNT_MONEY)
		{
			long remainAmount = AppMain.getInstance().getCurrentAccount().getAmount()
					- price;

			if (remainAmount < 0)
			{
				showDialogWithCatch(R.string.message_error_not_enough_money);
				hideProgressDialog();
				_timerOutUtils.resume();

				Utils.debug("Cancel timer!");
				_timerOutProductDelevery.cancel();
				_timerOutProductDelevery = null;
				return;
			}

			StandbyActivity.getInstance().usbSend(
					currentBox.getCommand() + ":" + remainAmount + CODE_END);

			_textUserAmount.setText(remainAmount + "VND");
		}
		else
		{
			StandbyActivity.getInstance().usbSend(currentBox.getCommand());
		}

		_productSell = new ProductSell();
		_productSell.setAccountNumber(AppMain.getInstance().getCurrentAccount().getId());
		_productSell.setIdBox(currentBox.getId());
		_productSell.setDelivered(false);
		_productSell.setSentServerOk(false);
		_productSell.setPrice(price);
		_productSell.setDate(System.currentTimeMillis());
		_productSell.setCodeProduct(currentBox.getProductCode());
		_productSell.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());

		TimerTask timerTask = new TimerTask()
		{

			@Override
			public void run()
			{
				cancel();

				Utils.debug("Time out delevery!");
				hideProgressDialog();

				_timerOutUtils.resume();

				showMessageError();
			}
		};
		_timerOutProductDelevery = new Timer();
		_timerOutProductDelevery.schedule(timerTask,
				Constant.TIME_OUT_WAIT_PRODUCT_DELIVERY);
	}

	@Override
	public void finish()
	{
		Utils.debug("Finish user!!!!!!!!!!!!!!!!");
		super.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (data == null)
			{
				Utils.debug("null data return!!!!!!!!!!!!!!!!!!1");
				return;
			}

			String dataString = data.getStringExtra(InputTextActivity.KEY_INPUT_DATA);

			if (dataString == null || dataString.equals(""))
			{
				Utils.debug("null data String!!!!!!!!!!!!!!!!!!1");

				return;
			}

			if (requestCode == InputTextActivity.INPUT_USER_AMOUNT)
			{
				// TODO Check the money code to return the money

				long moneyAmout = AppMain.getInstance().getCurrentAccount().getAmount() + 100000;
				AppMain.getInstance().getCurrentAccount().setAmount(moneyAmout);

				StandbyActivity.getInstance().usbSend(
						Constant.CODE_BLUETOOTH_PAY_MONEY_IN + ":" + moneyAmout
								+ CODE_END);

				showDialogWithCatch(R.string.message_success_pay_money_in);

				_textUserAmount.setText(moneyAmout + getString(R.string.vnd));
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_exit_confirm_user)
		{
			return new DialogMessageConfirm(this, false, id, true, true);
		}
		if (id == R.string.message_welcome_login)
		{
			// return new DialogMessageConfirm(this,
			// String.format(getString(id),
			// AppMain.getInstance()._accountCurrent.getName(),
			// AppMain.getInstance()._accountCurrent.getCellPhone()),
			// R.string.ok);

			return new DialogMessageTimeOut(this, String.format(getString(id),
					AppMain.getInstance().getCurrentAccount().getName(),
					AppMain.getInstance().getCurrentAccount().getId()));
		}
		if (id == R.string.message_success_pay_money_in)
		{
			final DialogMessageTimeOut dialogMessageTimeOut = new DialogMessageTimeOut(
					this,
					String.format(
							getString(id),
							AppMain.getInstance().getCurrentAccount().getAmount()),
					true);

			final TimerTask timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					runOnUiThread(new Runnable()
					{

						@Override
						public void run()
						{
							dialogMessageTimeOut.hide();
						}
					});
				}
			};

			dialogMessageTimeOut.setTimeTask(timerTask);

			return dialogMessageTimeOut;
		}
		if (id == R.string.message_confirm_buy_product)
		{
			final DialogMessageConfirm dialogMessageConfirmBuy = new DialogMessageConfirm(
					this,
					false,
					String.format(
							getString(R.string.message_confirm_buy_product),
							AppMain.getInstance().getCurrentBox().getProductCode()),
					false);
			OnClickListener onClickListenerYES = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					if (isBoughtProduct)
					{
						return;
					}

					isBoughtProduct = true;

					dialogMessageConfirmBuy.cancel();
					processBuyProduct();
				}
			};

			OnClickListener onClickListenerNo = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmBuy.cancel();
					_timerOutUtils.resume();
				}
			};

			dialogMessageConfirmBuy.setOnclickListenerYes(onClickListenerYES);
			dialogMessageConfirmBuy.setOnclickListenerNo(onClickListenerNo);
			return dialogMessageConfirmBuy;
		}
		else if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_error_not_enough_money)
		{
			return new DialogMessageBack(this, true, id, false);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
				}
			};
			dialogMessageConfirmNotOperating.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else if (id == R.string.message_put_command_error)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_put_command_ok)
		{
			return new DialogMessageBack(this, id);
		}
		else if (id == R.string.message_dialog_product)
		{
			String[] listFunctions = {
					getString(R.string.message_dialog_product_buy),
					getString(R.string.message_dialog_product_detail),
					getString(R.string.message_dialog_product_cancel) };
			final DialogList dialogList = new DialogList(this, listFunctions);

			OnItemClickListener onItemClickListener = new OnItemClickListener()
			{

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id)
				{

					_timerOutUtils.pause();

					dialogList.hide();

					switch (position)
					{
						case 0:
							runOnUiThread(new Runnable()
							{

								@Override
								public void run()
								{

									// _timerOutUtils.startTimeOutDialog();
									// showDialogWithCatch(R.string.message_confirm_buy_product);

									dialogMessageConfirmBuy = new DialogMessage(
											UserActivity.this, false);

									OnClickListener onClickListenerYES = new OnClickListener()
									{

										@Override
										public void onClick(View v)
										{
											if (isBoughtProduct)
											{
												return;
											}

											isBoughtProduct = true;

											dialogMessageConfirmBuy.hide();
											dialogMessageConfirmBuy = null;

											processBuyProduct();
										}
									};

									OnClickListener onClickListenerNo = new OnClickListener()
									{

										@Override
										public void onClick(View v)
										{
											dialogMessageConfirmBuy.hide();
											_timerOutUtils.resume();
											dialogMessageConfirmBuy = null;
										}
									};

									dialogMessageConfirmBuy.show(
											String.format(
													getString(R.string.message_confirm_buy_product),
													AppMain.getInstance().getCurrentBox().getProductCode()),
											onClickListenerYES,
											onClickListenerNo);

								}
							});
							break;

						case 1:
							isDetailProduct = true;
							Intent intent = new Intent(UserActivity.this,
									DetailProductActivity.class);
							startActivity(intent);
							break;
					}
				}
			};

			dialogList.setOnItemClickListener(onItemClickListener);

			return dialogList;

		}
		else
		{
			return createDialogStatusServer(id);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerNotOperating();

		return super.onTouchEvent(event);
	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();

		super.onPause();
	}

	@Override
	protected void onResume()
	{
		if (isDetailProduct)
		{
			_timerOutUtils.resume();
			isDetailProduct = false;
		}

		showProducts();
		super.onResume();
	}

	private void showProducts()
	{
		_productList = AppMain.getInstance().getProducts();

		int totalProducts = (_productList != null) ? _productList.size() : 0;
		_totalPages = (totalProducts != 0 && totalProducts
				% Constant.MAX_VIEWS_A_PAGE == 0) ? (totalProducts / Constant.MAX_VIEWS_A_PAGE)
				: (totalProducts / Constant.MAX_VIEWS_A_PAGE + 1);

		if (totalProducts == 0)
		{
			_textHaveNoProduct.setVisibility(View.VISIBLE);

			_listViewProduct1.setVisibility(View.GONE);
			_listViewProduct2.setVisibility(View.GONE);
			_listViewProduct3.setVisibility(View.GONE);

			_buttonPageBack.setVisibility(View.GONE);
			_buttonPageNext.setVisibility(View.GONE);
		}
		else
		{
			_textHaveNoProduct.setVisibility(View.GONE);

			_listViewProduct1.setVisibility(View.VISIBLE);
			_listViewProduct1.removeAllViews();
			_listViewProduct2.setVisibility(View.VISIBLE);
			_listViewProduct2.removeAllViews();
			_listViewProduct3.setVisibility(View.VISIBLE);
			_listViewProduct3.removeAllViews();

			final int startIndex = _pageCurrent * Constant.MAX_VIEWS_A_PAGE;
			final int endIndex = (_pageCurrent == _totalPages - 1) ? totalProducts
					: (startIndex + Constant.MAX_VIEWS_A_PAGE);

			Utils.debug("start index = " + startIndex + " end index = "
					+ endIndex);

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = startIndex; index < endIndex; index++)
			{
				final ViewHolder viewHolder = new ViewHolder();
				final View view = layoutInflater.inflate(
						R.layout.layout_one_product, null);

				viewHolder.imageViewProduct = (ImageView) view.findViewById(R.id.image_product);
				viewHolder.textProductName = (TextView) view.findViewById(R.id.text_product_name);
				viewHolder.textProductPrice = (TextView) view.findViewById(R.id.text_product_price);

				final BoxItem boxItem = _productList.get(index);
				viewHolder.textProductName.setText(boxItem.getProduct().getName()
						+ "");
				viewHolder.textProductPrice.setText(boxItem.getProduct().getPrice()
						+ "");
				viewHolder.textProductPrice.setVisibility(View.GONE);

				/* Image of the product */
				InputStream inputStream = null;
				try
				{
					inputStream = getAssets().open(
							"products/" + boxItem.getProduct().getCode()
									+ ".png");
				} catch (Exception e)
				{
					e.printStackTrace();
					inputStream = null;
				}

				if (inputStream != null)
				{
					Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
					viewHolder.imageViewProduct.setImageBitmap(bitmap);
				}

				((LinearLayout) view.findViewById(R.id.layout_product_one)).setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View arg0)
					{
						if (isBoughtProduct)
						{
							return;
						}

						AppMain.getInstance().updateCurrentBox(
								boxItem.getBox().getId());

						showDialogWithCatch(R.string.message_dialog_product);
					}
				});

				if (index - startIndex < Constant.MAX_VIEWS_A_COLUMN)
				{
					_listViewProduct1.addView(view);
				}
				else if (index - startIndex < (Constant.MAX_VIEWS_A_COLUMN << 1))
				{
					_listViewProduct2.addView(view);
				}
				else
				{
					_listViewProduct3.addView(view);
				}

			}

		}

		if (_pageCurrent == 0 || _totalPages == 1)
		{
			_buttonPageBack.setVisibility(View.GONE);
			_buttonPageTemp.setVisibility(View.GONE);
		}
		if (_pageCurrent == _totalPages - 1 || _totalPages == 1)
		{
			_buttonPageNext.setVisibility(View.GONE);
			_buttonPageTemp.setVisibility(View.GONE);
		}

		if (_buttonPageBack.getVisibility() == View.VISIBLE
				&& _buttonPageNext.getVisibility() == View.VISIBLE)
			_buttonPageTemp.setVisibility(View.INVISIBLE);
	}

	@Override
	protected void onDestroy()
	{
		hideProgressDialog();
		System.gc();
		super.onDestroy();
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event)
	// {
	// if (keyCode == KeyEvent.KEYCODE_SEARCH
	// && (event.getFlags() & KeyEvent.FLAG_LONG_PRESS) ==
	// KeyEvent.FLAG_LONG_PRESS) {
	// return true;
	// }
	//
	// return true;
	// }
	//
	// @Override
	// public boolean onKeyUp(int keyCode, KeyEvent event)
	// {
	//
	//
	// return true;
	// }

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:

				showDialogWithCatch(R.string.message_time_out_user_not_operating);

				break;
			case TIME_OUT_USER:

				showDialogWithCatch(R.string.message_time_out_user);

				break;
			case PUT_PRODUCT_ERROR:

				showMessageError();
				break;
			// case PUT_PRODUCT_OK:
			// showDialogWithCatch(R.string.message_put_command_ok);
			//
			// _timerOutUtils.startTimeOutDialog(MAIN_CONFIG.TIME_OUT_WAIT_DIALOG_BUY_PRODUCT_SUCESS);
			//
			// /* Put out the product */
			//
			// /* Process the money */
			// long currentAmount =
			// AppMain.getInstance()._accountCurrent.getAmount();
			// AppMain.getInstance()._accountCurrent.setAmount(currentAmount
			// + getCurrentProduct().getPrice());
			// _accountSqLite.insert(AppMain.getInstance()._accountCurrent);
			//
			// if (MAIN_CONFIG.IS_DEBUG)
			// {
			// Utils.debug("amount before = " + currentAmount);
			// Account account =
			// _accountSqLite.getById(AppMain.getInstance()._accountCurrent.getId());
			// if (account != null)
			// Utils.debug("amount now = " +
			// account.getAmount());
			// else
			// Utils.debug("amount now = error----------------");
			// }
			//
			// /* Update box */
			// int currentProductCount =
			// AppMain.getInstance().getCurrentBox().getProductAmount();
			// AppMain.getInstance().getCurrentBox().setProductAmount(currentProductCount
			// -
			// 1);
			// _boxSqLite.insert(AppMain.getInstance().getCurrentBox());
			//
			// if (MAIN_CONFIG.IS_DEBUG)
			// {
			// Utils.debug("product count before = "
			// + currentProductCount);
			// Box box =
			// _boxSqLite.getById(AppMain.getInstance().getCurrentBox().getId());
			//
			// if (box != null)
			// Utils.debug("count now = " +
			// box.getProductAmount());
			// else
			// Utils.debug("product count now = error----------------");
			// }
			//
			// if (AppMain.getInstance().getCurrentBox().getProductAmount() ==
			// 0)
			// {
			// AppMain.getInstance().getProducts(this);
			// showProducts();
			// }
			//
			// if (!MAIN_CONFIG.USE_SEND_ALL_DATA)
			// {
			// if (MAIN_CONFIG.IS_NETWORK_AVAILABLE)
			// Network.sendProductSell(_productSell,
			// AppMain.getInstance().getMachine(this));
			// }
			//
			// break;

			default:
				break;
		}
		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	@Override
	public void onConnectFail(int typeError)
	{
		Utils.debug("Connect fail!.......................");
		hideProgressDialog();

		showDialogWithStatus(typeError);
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (transaction.getModel() == null)
		{
			Utils.debug("Model null------------");
		}

		if (transaction.getMethodSent().equals(
				CONSTANTS.SERVICE.ADD_PRODUCT_SELLOUT))
		{
			if (message.toUpperCase().contains("OK"))
			{
				ProductSell productSell = (ProductSell) transaction.getModel();
				productSell.setSentServerOk(true);
				_productSellSQLite.insert(productSell);
			}
		}
	}

	@Override
	public void onReceivedUsbMessage(String message)
	{
		Utils.debug("Full USB message : " + message);

		if (_timerOutProductDelevery != null)
		{
			_timerOutUtils.resume();

			Utils.debug("Cancel timer!");
			_timerOutProductDelevery.cancel();
			_timerOutProductDelevery = null;

			setResult(RESULT_OK);

			if (!message.equalsIgnoreCase(CODE_OK))
			{
				showMessageError();
			}
			else
			{
				Utils.debug("hide waiting dialog!!!");
				hideProgressDialog();

				if (_timerOutProductDelevery != null)
				{
					Utils.debug("Cancel timer!");
					_timerOutProductDelevery.cancel();
				}

				/* Put out the product */
				_productSell.setDelivered(true);

				_productSellSQLite.insert(_productSell);

				if (!AppConfig.USE_SEND_ALL_DATA)
				{
					if (AppConfig.IS_NETWORK_AVAILABLE)
					{
						_productSellSQLite.updateIdDB(_productSell);
						Network.sendProductSell(_productSell,
								AppMain.getInstance().getMachineInfo());
					}
				}

				_productSell = null;

				/* Process the money */
				long currentAmount = AppMain.getInstance().getCurrentAccount().getAmount();
				long price = AppMain.getInstance().getCurrentBoxItem().getProduct().getPrice();
				AppMain.getInstance().getCurrentAccount().setAmount(
						currentAmount + price);
				_accountSqLite.insert(AppMain.getInstance().getCurrentAccount());

				if (AppConfig.IS_DEBUG)
				{
					Utils.debug("amount before = " + currentAmount);
					Account account = _accountSqLite.getById(AppMain.getInstance().getCurrentAccount().getId());
					if (account != null)
						Utils.debug("amount now = " + account.getAmount());
					else
						Utils.debug("amount now = error----------------");
				}

				/* Update box */
				int currentProductCount = AppMain.getInstance().getCurrentBox().getProductAmount();
				AppMain.getInstance().getCurrentBox().setProductAmount(
						currentProductCount - 1);

				_boxSqLite.insert(AppMain.getInstance().getCurrentBox());
				AppMain.getInstance().updateListBoxItems();

				if (AppConfig.IS_DEBUG)
				{
					Utils.debug("product count before = " + currentProductCount);

					Box box = _boxSqLite.getById(AppMain.getInstance().getCurrentBox().getId());

					if (box != null)
						Utils.debug("count now = " + box.getProductAmount());
					else
						Utils.debug("product count now = error----------------");
				}

				_timerOutUtils.startTimeOutDialog(Constant.TIME_OUT_WAIT_DIALOG_BUY_PRODUCT_SUCESS);

				runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{

						showDialogWithCatch(R.string.message_put_command_ok);

					}
				});
			}
		}
	}

}
